/*
 * Hibiscus is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published
 * by the Free Software Foundation; either version 3 of the License,
 * or (at your option) any later version.
 *
 * Hibiscus is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Hibiscus; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA
 *
 * Copyright (C) 2011 Tetete - http://tetete.hu.
 */
package hu.tetete.hibiscus.edittaxon;

import java.io.File;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import hu.tetete.hibiscus.R;
import hu.tetete.hibiscus.model.Taxon;
import hu.tetete.hibiscus.model.TaxonLevel;

/**
 * TODO javadoc.
 */
public class EditTaxonActivity extends EditTaxonAbstractActivity {

    /** Logger's tag. */
    static final String TAG = EditTaxonActivity.class.getName();

    /** Possible activity request codes */
    private static final int PICK_FROM_CAMERA = 1;
    private static final int PICK_FROM_FILE   = 2;

    /** Contains the possible extra parameters what the class can get from {@link Intent}. */
    public enum INTENT_EXTRA {
        /** The parent taxon of the new taxon. (Nullable) */
        PARENT_TAXON,
        /** The taxon which will be edited. (Nullable) */
        EDIT_TAXON,
    }

    private Taxon editTaxon;
    private File  tempFile;

    /**
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    protected void onCreate(final Bundle savedInstanceState) {

        final Intent incomeIntent = getIntent();



        super.onCreate(savedInstanceState, new ServiceConnection() {

            @Override
            public void onServiceDisconnected(final ComponentName name) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onServiceConnected(final ComponentName name, final IBinder service) {

                /* Service initialization */
                editTaxon = (Taxon)incomeIntent.getExtras().get(INTENT_EXTRA.EDIT_TAXON.name());
                Log.i(TAG, "EditTaxon: " + editTaxon);
                EditTaxonActivity.this.editTaxonService.initiateByTaxon(editTaxon);
                if (editTaxon == null) {
                    EditTaxonActivity.this.editTaxonService.setParentTaxon((Taxon)incomeIntent.getExtras().get(INTENT_EXTRA.PARENT_TAXON.name()));
                }

                /* View initialization */
                final Taxon  parentTaxon  = EditTaxonActivity.this.editTaxonService.getParentTaxon();

                setContentView(R.layout.edit_taxon_details);

                final TextView  taxonName        = (TextView)findViewById(R.id.taxonName);
                final TextView  scienceName      = (TextView)findViewById(R.id.scienceName);
                final ImageView taxonImage       = (ImageView)findViewById(R.id.taxonImage);
                final EditText  taxonNameField   = (EditText)findViewById(R.id.taxonNameInput);
                final EditText  scienceNameField = (EditText)findViewById(R.id.scienceNameInput);
                final Spinner   taxonLevel       = (Spinner)findViewById(R.id.taxonLevel);
                final ImageView editTaxonImage   = (ImageView)findViewById(R.id.editTaxonImage);
                final View      nextButton       = findViewById(R.id.nextButton);

                final TaxonLevel[] allTaxonLevel           = TaxonLevel.values();
                final int          parentTaxonLevelOrdinal = parentTaxon == null ? 0 : parentTaxon.getTaxonLevel().ordinal() + 1;
                final TaxonLevel[] taxonLevels             = new TaxonLevel[allTaxonLevel.length - parentTaxonLevelOrdinal];

                for (int i = parentTaxonLevelOrdinal; i < allTaxonLevel.length; i++) {
                    taxonLevels[i - parentTaxonLevelOrdinal] = allTaxonLevel[i];
                }

                taxonLevel.setAdapter(new ArrayAdapter<TaxonLevel>(EditTaxonActivity.this, android.R.layout.simple_spinner_item, taxonLevels));

                nextButton.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(final View v) {
                        final CharSequence taxonNameString = taxonNameField.getText();
                        if (taxonNameString == null || taxonNameString.toString().length() == 0) {
                            Toast.makeText(EditTaxonActivity.this, "Taxon name is empty", Toast.LENGTH_LONG).show();
                            taxonNameField.requestFocus();
                            return;
                        }
                        final CharSequence scienceNameString = scienceNameField.getText();
                        if (scienceNameString == null || scienceNameString.toString().length() == 0) {
                            Toast.makeText(EditTaxonActivity.this, "Science name is empty", Toast.LENGTH_LONG).show();
                            scienceNameField.requestFocus();
                            return;
                        }
                        final TaxonLevel selectedLevel = (TaxonLevel) taxonLevel.getSelectedItem();

                        EditTaxonActivity.this.editTaxonService.setName(taxonNameString.toString());
                        EditTaxonActivity.this.editTaxonService.setScienceName(scienceNameString.toString());
                        EditTaxonActivity.this.editTaxonService.setTaxonLevel(selectedLevel);
                        final Intent newTaxonIntent = new Intent(EditTaxonActivity.this, EditTaxonPropertyTreeActivity.class);
                        startActivity(newTaxonIntent);

                    }
                });

                /* View content initialization */
                Log.i(TAG, "Name: " + EditTaxonActivity.this.editTaxonService.getName());
                taxonNameField.setText(EditTaxonActivity.this.editTaxonService.getName());
                scienceNameField.setText(EditTaxonActivity.this.editTaxonService.getScienceName());
                if (EditTaxonActivity.this.editTaxonService.getId() != null) {
                    taxonName.setText(EditTaxonActivity.this.editTaxonService.getName());
                    scienceName.setText(editTaxonService.getScienceName());
                } else {
                    scienceName.setText(null);
                }

                if (EditTaxonActivity.this.editTaxonService.getTaxonLevel() != null) {
                    taxonLevel.setSelection(EditTaxonActivity.this.editTaxonService.getTaxonLevel().ordinal() - parentTaxonLevelOrdinal, true);
                }

                final File taxonPhoto = editTaxonService.getPhoto();
                if (taxonPhoto != null) {
                    editTaxonImage.setImageURI(Uri.fromFile(taxonPhoto));
                    taxonImage.setImageURI(Uri.fromFile(taxonPhoto));
                }
                editTaxonImage.setOnClickListener(new NewPhotoOnClickListener());

                taxonNameField.requestFocus();
            }
        });
    }

    private class NewPhotoOnClickListener implements View.OnClickListener {

        /** {@inheritDoc} */
        @Override
        public void onClick(final View v) {

            final String storageState = Environment.getExternalStorageState();

            /* If no SD card we will show an error message */
            if(!storageState.equals(Environment.MEDIA_MOUNTED)) {
                new AlertDialog.Builder(EditTaxonActivity.this)
                .setMessage("External Storeage (SD Card) is required.\n\nCurrent state: " + storageState)
                .setCancelable(true).create().show(); //TODO change this error message.
            }

            /* Take photo or select from gallery */
            final String []            items   = new String [] {"Take from camera", "Select from gallery"}; //TODO from resource file.
            final ArrayAdapter<String> adapter = new ArrayAdapter<String>(EditTaxonActivity.this, android.R.layout.select_dialog_item, items);
            final AlertDialog.Builder  builder = new AlertDialog.Builder(EditTaxonActivity.this);

            builder.setTitle("Select Image");
            builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, final int item) { //pick from camera
                    tempFile = getTempFile(); //TODO use create temporary file. File.createTempFile()
                    //TODO check space on the card.
                    try {
                        if (!tempFile.exists()) {
                            tempFile.getParentFile().mkdirs();
                            tempFile.createNewFile();
                        }
                    } catch (final Exception e) {
                        Log.e(TAG, "Couldn't create file for the photo.", e);
                        Toast.makeText(EditTaxonActivity.this, "Couldn't create file for the photo.", Toast.LENGTH_LONG).show();
                        //TODO close or send error to me :-)
                    }
                    final Uri mImageCaptureUri = Uri.fromFile(tempFile);
                    if (item == 0) {
                        final Intent intent      = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                        intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
                        intent.putExtra("outputFormat",    Bitmap.CompressFormat.JPEG.toString());
                        intent.putExtra("crop",            "true");
                        intent.putExtra("return-data",     false);
                        intent.putExtra("outputX",         200);
                        intent.putExtra("outputY",         200);
                        intent.putExtra("aspectX",         1);
                        intent.putExtra("aspectY",         1);
                        intent.putExtra("scale",           true);
                        intent.putExtra("noFaceDetection", true);

                        try {
                            startActivityForResult(intent, PICK_FROM_CAMERA);
                        } catch (final ActivityNotFoundException e) {
                            e.printStackTrace();
                            Toast.makeText(EditTaxonActivity.this, "Couldn't take a photo from camera.", Toast.LENGTH_LONG).show();
                        }
                    } else { //pick from file
                        final Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);

                        intent.setType("image/*");
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
                        intent.putExtra("outputFormat",    Bitmap.CompressFormat.JPEG.toString());
                        intent.putExtra("crop",            "true");
                        intent.putExtra("return-data",     false);
                        intent.putExtra("outputX",         200);
                        intent.putExtra("outputY",         200);
                        intent.putExtra("aspectX",         1);
                        intent.putExtra("aspectY",         1);
                        intent.putExtra("scale",           true);
                        intent.putExtra("noFaceDetection", true);

                        try {
                            startActivityForResult(intent, PICK_FROM_FILE);
//                            startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
                        } catch (final ActivityNotFoundException e) {
                            e.printStackTrace();
                            Toast.makeText(EditTaxonActivity.this, "Couldn't take a photo from gallery.", Toast.LENGTH_LONG).show();
                        }
                    }
                }
            });
            builder.create().show();
        }

        File getTempFile() {
            final File tempFile = new File(Environment.getExternalStorageDirectory(),
                    "tmp_taxonphoto_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
            tempFile.deleteOnExit();
            return tempFile;
        }
    }

    /**
     * @see Activity#onActivityResult(int, int, Intent)
     */
    @Override
    protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PICK_FROM_FILE :
            case PICK_FROM_CAMERA : {
                if (resultCode == RESULT_OK) {
                    if (data == null) {
                        Log.w(TAG, "Null data, but RESULT_OK, from image picker!");
                        Toast.makeText(this, "Null data, but RESULT_OK, from image picker", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    final ImageView taxonImage  = (ImageView)findViewById(R.id.taxonImage);

                    editTaxonService.setPhoto(tempFile, true);
                    taxonImage.setImageURI(Uri.fromFile(tempFile));

                    Log.w(TAG, "Photo stored.");

                    return;
                }
                Log.w(TAG, "ResultCode FALSE!");
                Toast.makeText(this, "ResultCode FALSE", Toast.LENGTH_SHORT).show();
                return;
                //TODO remove file!!!
            }
            default : {
                Log.w(TAG, "Something doesn't work. ResquestCode: " + requestCode + " resultCode: " + resultCode);
            }
        }
    }



}
